#include "Thread.hpp"
#include <vector>
int num = 10000;



class ThreadData
{
public:
    std::string _name;
    pthread_mutex_t* lock_ptr;
};

void tickets(ThreadData& lock)
{
    while (true)
    {
        // pthread_mutex_lock(lock.lock_ptr);
        int n = pthread_mutex_trylock(lock.lock_ptr);
        if (n != 0)
        {
            printf("%s没有进行加锁，因为临界区已经被锁住了\n", lock._name.c_str());
        }
        if (num > 0)
        {
            // usleep(1000); //没有加保护
            printf("thread: %s , get a tick : %d\n", lock._name.c_str(),num--);
            pthread_mutex_unlock(lock.lock_ptr);

            //还要做别的操作，不然一个进程解锁之后立马又去申请锁
            usleep(50); //效率奇高
        }
        else 
        {
            pthread_mutex_unlock(lock.lock_ptr);
            break;
        }
    }
}


#define MX 4
int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock,nullptr);

    std::vector<MyPhread_Modle::Thread<ThreadData>> threads;
    for (int i = 0; i < 4; i++)
    {
        ThreadData* td = new ThreadData();
        td->lock_ptr = &lock;
        threads.emplace_back(tickets,*td);
        td->_name = threads.back().Name();
    }

    for (auto &thread : threads)
    {
        thread.Start();
    }

    for (auto &thread : threads)
    {
        thread.Join();
    }

    return 0;
}